<template>
  <div>
    <el-tree ref="tree" node-key="id" show-checkbox default-expand-all :data="list" check-strictly :props="{label:'name',children:'children'}" />
    <template>
      <div style="text-align: right;">
        <el-button @click="$emit('close')">取消</el-button>
        <el-button type="primary" @click="hSubmit">确定</el-button>
      </div>
    </template>
  </div>
</template>

<script>
import { getPermissionList } from '@/api/modules/permisson'
import { transDataToTreeData } from '@/utils/index'
import { getRoleDetail, assignPerm } from '@/api/modules/settings'

export default {
  props: {
    roleId: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      list: [] // 获取权限列表
    }
  },
  created() {
    this.loadPermissionList()
    this.loadRoleDetail()
  },
  methods: {
    // 给角色分配权限
    async hSubmit() {
      // console.log(this.$refs.tree.getCheckedKeys())
      const permIds = this.$refs.tree.getCheckedKeys()
      try {
        const res = await assignPerm({ id: this.roleId, permIds: permIds })
        console.log('assignPerm', res)
        this.$emit('close')
      } catch (err) {
        console.log('assignPerm', err)
      }
    },
    // 获取角色详情
    async loadRoleDetail() {
      try {
        const res = await getRoleDetail(this.roleId)
        console.log('getRoleDetail', res)
        this.$refs.tree.setCheckedKeys(res.data.permIds)
        // 保存数据
      } catch (err) {
        console.log('getRoleDetail', err)
      }
    },
    // 获取权限列表
    async loadPermissionList() {
      try {
        const res = await getPermissionList()
        console.log('getPermissionList', res)
        this.list = transDataToTreeData(res.data)
        // 保存数据
      } catch (err) {
        console.log('getPermissionList', err)
      }
    }
  }
}
</script>

<style>

</style>
